package com.bw.mine.login

import android.Manifest
import android.annotation.TargetApi
import android.app.KeyguardManager
import android.content.Context
import android.content.pm.PackageManager
import android.hardware.fingerprint.FingerprintManager
import android.os.Build
import android.os.Bundle
import android.security.keystore.KeyGenParameterSpec
import android.security.keystore.KeyPermanentlyInvalidatedException
import android.security.keystore.KeyProperties
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.bw.common.mvvm.BaseViewActivity
import com.bw.mine.R
import com.bw.mine.databinding.ActivityFingerprintLoginBinding
import com.bw.mine.login.viewmodel.FingerprintViewModel
import com.therouter.TheRouter
import com.therouter.router.Route
import java.security.KeyStore
import javax.crypto.Cipher
import javax.crypto.KeyGenerator
import javax.crypto.SecretKey
@Route(path = "/mine/FingerprintLoginActivity")
class FingerprintLoginActivity : BaseViewActivity<ActivityFingerprintLoginBinding>() {
    private lateinit var viewModel: FingerprintViewModel
    // 指纹相关工具类
    private lateinit var keyguardManager: KeyguardManager
    private lateinit var fingerprintManager: FingerprintManager
    private lateinit var cipher: Cipher
    private val KEY_NAME = "fingerprint_key"
    override fun initData() {

    }

    override fun initView() {
// 初始化 ViewModel
        viewModel = FingerprintViewModel()
        // 绑定生命周期所有者（确保LiveData随Activity生命周期更新）
        binding.lifecycleOwner = this
        binding.usePasswordButton.setOnClickListener {
            TheRouter.build("/mine/LoginActivity").navigation()
        }

        // 初始化指纹识别
        initFingerprint()
    }

    private fun initFingerprint() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            keyguardManager = getSystemService(Context.KEYGUARD_SERVICE) as KeyguardManager
            fingerprintManager = getSystemService(Context.FINGERPRINT_SERVICE) as FingerprintManager

            // 检查设备是否支持指纹识别
            if (!isFingerprintAvailable()) return

            // 初始化加密工具并开始认证
            if (initCipher()) {
                val cryptoObject = FingerprintManager.CryptoObject(cipher)
                val handler = FingerprintCallback()
                startAuth(handler, cryptoObject)
            }
        } else {
            viewModel.updateError("设备版本过低，不支持指纹识别")
        }
    }

    // 检查指纹识别是否可用
    private fun isFingerprintAvailable(): Boolean {
        // 检查权限
        if (ActivityCompat.checkSelfPermission(
                this,
                Manifest.permission.USE_FINGERPRINT
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            ActivityCompat.requestPermissions(
                this,
                arrayOf(Manifest.permission.USE_FINGERPRINT),
                100
            )
            return false
        }

        // 检查硬件支持
        if (!fingerprintManager.isHardwareDetected) {
            viewModel.updateError("设备没有指纹传感器")
            return false
        }

        // 检查是否已录入指纹
        if (!fingerprintManager.hasEnrolledFingerprints()) {
            viewModel.updateError("请先在设置中录入指纹")
            return false
        }

        // 检查锁屏安全性
        keyguardManager = getSystemService(Context.KEYGUARD_SERVICE) as KeyguardManager
        if (!keyguardManager.isKeyguardSecure) {
            viewModel.updateError("请先设置锁屏密码")
            return false
        }

        // 初始化加密工具并开始认证
        viewModel.updateStatus("请将手指放在指纹传感器上")
        return true
    }

    // 初始化加密算法（用于指纹验证的安全机制）
    @TargetApi(Build.VERSION_CODES.M)
    private fun initCipher(): Boolean {
        try {
            val keyStore = KeyStore.getInstance("AndroidKeyStore")
            val keyGenerator = KeyGenerator.getInstance(
                KeyProperties.KEY_ALGORITHM_AES,
                "AndroidKeyStore"
            )

            keyStore.load(null)
            keyGenerator.init(
                KeyGenParameterSpec.Builder(
                    KEY_NAME,
                    KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT
                )
                    .setBlockModes(KeyProperties.BLOCK_MODE_CBC)
                    .setUserAuthenticationRequired(true) // 要求用户认证才能使用密钥
                    .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7)
                    .build()
            )
            keyGenerator.generateKey()

            // 初始化Cipher
            cipher = Cipher.getInstance(
                "${KeyProperties.KEY_ALGORITHM_AES}/${KeyProperties.BLOCK_MODE_CBC}/${KeyProperties.ENCRYPTION_PADDING_PKCS7}"
            )
            val key = keyStore.getKey(KEY_NAME, null) as SecretKey
            cipher.init(Cipher.ENCRYPT_MODE, key)
            return true
        } catch (e: KeyPermanentlyInvalidatedException) {
            // 密钥失效（如指纹被删除），需要重新生成密钥
            return false
        } catch (e: Exception) {
            throw RuntimeException("初始化加密工具失败", e)
        }
    }

    // 开始指纹认证
    @TargetApi(Build.VERSION_CODES.M)
    private fun startAuth(handler: FingerprintCallback, cryptoObject: FingerprintManager.CryptoObject) {
        if (ActivityCompat.checkSelfPermission(
                this,
                Manifest.permission.USE_FINGERPRINT
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            return
        }
        fingerprintManager.authenticate(
            cryptoObject,
            null, // 取消信号（可选，用于中断认证）
            0,
            handler,
            null
        )
    }

    // 指纹认证回调（处理认证结果）
    inner class FingerprintCallback : FingerprintManager.AuthenticationCallback() {
        override fun onAuthenticationSucceeded(result: FingerprintManager.AuthenticationResult) {
            super.onAuthenticationSucceeded(result)
            viewModel.updateStatus("指纹认证成功！")
            viewModel.updateError(null) // 清空错误信息
            // 认证成功，可跳转至主界面
            Toast.makeText(this@FingerprintLoginActivity, "登录成功", Toast.LENGTH_SHORT).show()
        }

        override fun onAuthenticationFailed() {
            super.onAuthenticationFailed()
            viewModel.updateError("指纹不匹配，请重试")
        }

        override fun onAuthenticationError(errorCode: Int, errString: CharSequence) {
            super.onAuthenticationError(errorCode, errString)
            viewModel.updateError("认证错误：$errString")
        }

        override fun onAuthenticationHelp(helpCode: Int, helpString: CharSequence) {
            super.onAuthenticationHelp(helpCode, helpString)
            viewModel.updateStatus("提示：$helpString") // 显示帮助信息（如“请清洁传感器”）
        }
    }

    // 权限请求结果回调
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == 100) {
            if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                initFingerprint() // 权限通过后重新初始化
            } else {
                viewModel.updateError("需要指纹权限才能使用该功能")
            }
        }
    }
}